package com.boot.security.server.utils.mffl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * reids缓存
 */
@Component
public class MfflRedisUtil {

    //配置过期秒数
    @Value("${Pay.payConfirmSeconds}")
    private Integer payConfirmSeconds;

    //redis
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 拼接redis前缀，组成文件形式。
     * @param prefix 前缀
     * @param key    key
     * @return
     */
    private String getPayKey(String prefix, String key) {
        return prefix + ":" + key;
    }



    /**
     * redis存储
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public String saveRedis(String prefix, String key, String value) {
        try {
            if (StringUtils.isEmpty(prefix)) {
                redisTemplate.boundValueOps(key).set(value, payConfirmSeconds, TimeUnit.SECONDS);
            } else {
                redisTemplate.boundValueOps(getPayKey(prefix, key)).set(value, payConfirmSeconds, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
        return "ok";
    }



    /**
     * 获取值
     *
     * @param prefix 前缀
     * @param key    key
     * @return
     */
    public String getRedis(String prefix, String key) {
        String value = "";
        try {
            if (StringUtils.isEmpty(prefix)) {
                value = redisTemplate.opsForValue().get(key);
            } else {
                value = redisTemplate.opsForValue().get(getPayKey(prefix, key));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return value;
        }
        return value;
    }
}
